#include "MIconButton.h"

#include <QPainter>
#include <QStyleOption>

MIconButton::MIconButton(QWidget *parent) : QPushButton(parent)
{
}

void MIconButton::setTextContent(const QString &text)
{
    textContent_ = text;
}

void MIconButton::setIconIndex(YunXiuIconFont::IconIndex nIndex, int fontSize, int width)
{
    iconIndex_ = nIndex;
    iconFontSize_ = fontSize;
    iconWidth_ = width;
}

void MIconButton::setTextNormalStyle(QColor color)
{
    normalColor_ = color;
}
void MIconButton::setTextHoverStyle(QColor color)
{
    hoverColor_ = color;
}
void MIconButton::setTextDisableStyle(QColor color)
{
    disableColor_ = color;
}

void MIconButton::showEvent(QShowEvent *e)
{
    QPushButton::showEvent(e);

    auto margins = this->contentsMargins();
    QFontMetrics metrics = this->fontMetrics();
    auto textWidth = metrics.horizontalAdvance(textContent_);
    if (iconIndex_ != YunXiuIconFont::kIconEmpty)
    {
        textWidth += iconWidth_;
    }

    setFixedWidth(textWidth + 30);
}

void MIconButton::paintEvent(QPaintEvent *)
{

    QPainter painter(this);

    // 创建 QStyleOptionButton 对象并初始化
    QStyleOptionButton option;
    option.initFrom(this);

    // 获取 QStyle 对象
    QStyle *style = this->style();

    // 绘制按钮背景
    style->drawControl(QStyle::CE_PushButton, &option, &painter, this);

    QColor textColor;
    if (!isEnabled())
    {
        textColor = disableColor_;
    }
    else if (option.state & QStyle::State_MouseOver)
    {
        textColor = hoverColor_;
    }
    else
    {
        textColor = normalColor_;
    }

    // 获取按钮的边距信息
    QRect textRect = style->subElementRect(QStyle::SE_PushButtonContents, &option, this);

    if (iconIndex_ != YunXiuIconFont::kIconEmpty)
    {
        QRect iconRect = textRect;
        iconRect.setWidth(iconWidth_);
        textRect.adjust(iconWidth_, 0, 0, 0);
        painter.save();
        QFont font;
        font.setFamily("yunxiufontV2");
        font.setPixelSize(iconFontSize_);
        painter.setFont(font);
        painter.setPen(textColor);
        painter.drawText(iconRect, Qt::AlignCenter, QChar(iconIndex_));
        painter.restore();
    }

    painter.setPen(textColor);
    painter.drawText(textRect, Qt::AlignLeft | Qt::AlignVCenter, textContent_);
}
